﻿using Devonline.Communication.Abstractions;
using Devonline.Communication.Messages;
using Devonline.Entity;
using Microsoft.Extensions.Logging;

namespace SerialPortWithCommunicator;

internal class Communicator : MessageCommunicator, IMessageCommunicator
{
    private readonly ICommunicator _serialPortCommunicator;

    public Communicator(ILogger<Communicator> logger, ICommunicator communicator, MessageOptions messageOptions) : base(logger, messageOptions)
    {
        _serialPortCommunicator = communicator;
    }

    public override async Task StartAsync()
    {
        await base.StartAsync();
        await _serialPortCommunicator.StartAsync();
    }

    public override async Task StopAsync()
    {
        _serialPortCommunicator.Receive -= OnSerialPortReceiveData;
        await _serialPortCommunicator.StopAsync();
        await base.StopAsync();
    }

    protected override void OnInitial()
    {
        _serialPortCommunicator.Receive += OnSerialPortReceiveData;
        base.OnInitial();
    }

    protected override void OnReceive(Message message)
    {
        if (!string.IsNullOrWhiteSpace(message.Content))
        {
            _serialPortCommunicator.SendAsync(message.Content);
        }

        base.OnReceive(message);
    }

    private async void OnSerialPortReceiveData(object? sender, string value)
    {
        await SendAsync(value);
    }
}